package com.ls.business.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.business.entity.Leave;
import com.ls.business.mapper.LeaveMapper;
import com.ls.business.service.ILeaveService;
import com.ls.common.Constast;
import com.ls.common.DataGridView;
import com.ls.common.PageModel;
import com.ls.common.ResultObj;
import com.ls.common.utils.WebUtils;
import com.ls.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author lisheng
 * @Date 2025/05/07 16:05
 **/
@RestController
@RequestMapping("/leave")
public class LeaveController {

    @Autowired
    private ILeaveService leaveService;

    @Autowired
    private LeaveMapper leaveMapper;

    @GetMapping("/list")
    public DataGridView list(PageModel pageModel, HttpServletRequest request) {
        // 1. 获取当前登录用户
        SysUser u = (SysUser) WebUtils.getSession().getAttribute("user");
        if (u == null) {
            return new DataGridView(0L, null); // 或抛出异常提示未登录
        }

        // 2. 构建查询条件：system账号查全部，其他用户查自己
        QueryWrapper<Leave> queryWrapper = new QueryWrapper<>();
        if (!"system".equals(u.getLoginname())) {
            queryWrapper.eq("applicant", u.getLoginname()); // 假设字段名为 applicant
        }

        // 3. 分页查询
        Page<Leave> page = new Page<>(pageModel.getPage(), pageModel.getLimit());
        Page<Leave> leavePage = leaveService.page(page, queryWrapper);
        return new DataGridView(leavePage.getTotal(), leavePage.getRecords());
    }

    @PostMapping("/save")
    public ResultObj save(@RequestBody Leave leave) {
        try {
            SysUser u = (SysUser) WebUtils.getSession().getAttribute("user");
            if (ObjectUtil.isEmpty(u)) {
                return new ResultObj(Constast.ERROR, "操作失败：用户未登录！");
            }

            // 计算请假天数
            if (leave.getStartTime() != null && leave.getEndTime() != null) {
                long diff = leave.getEndTime().getTime() - leave.getStartTime().getTime();
                long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS) + 1; // 包含当天
                leave.setDays((int) days);
            } else {
                return new ResultObj(Constast.ERROR, "开始时间和结束时间不能为空");
            }

            if (ObjectUtil.isEmpty(leave.getId())) {
                leave.setApplicant(u.getName());
                leave.setApplicantId(u.getId());
                leave.setCode("QJ" + System.currentTimeMillis());
            }

            boolean success = leaveService.saveOrUpdate(leave);
            return success ? new ResultObj(Constast.OK, "操作成功") : new ResultObj(Constast.ERROR, "操作失败");
        } catch (Exception e) {
            return new ResultObj(Constast.ERROR, "操作失败：" + e.getMessage());
        }
    }


    @DeleteMapping("/{id}/delete") // 使用 DELETE 方法
    public ResultObj delete(@PathVariable Integer id) {
        boolean success = leaveService.removeById(id);
        return success ? ResultObj.DELETE_SUCCESS : ResultObj.DELETE_ERROR;
    }
}
